package cn.tedu._03vehicle.base.interceptors;

import cn.tedu._03vehicle.pojo.vo.UserVO;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 登录状态校验拦截器
 */
@Slf4j
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.debug("进入登录状态校验的拦截器...");
        /*
            1.获取会话session:  HttpSession session = request.getSession();
            2.从会话中获取用户标识
            3.判断用户标识是否为null
            4.如果用户标识为null,说明未登录
              4.1 重定向到登录页面: response.sendRedirect("/login.html");
              4.2 return false;
            5.用户标识不为null,说明已登录
              5.1 放行: return true;
         */
        HttpSession session = request.getSession();
        UserVO userVO = (UserVO) session.getAttribute("user");
        if (userVO == null){ // 未登录
            // http://localhost:8080/login.html
            response.sendRedirect("/login.html");
            return false;
        }
        // 放行
        return true;
    }
}
